<template>
  <div class="dashboard-container">
    <!-- 功能列表 -->
    <div class="function-section">
      <el-button type="primary" plain @click="showPendingBuyMonitor" class="function-btn">
        <i class="el-icon-price-tag"></i>
        待买入池对应股价
      </el-button>
      <el-button type="success" plain @click="showAllProfitStatistics" class="function-btn">
        <i class="el-icon-data-analysis"></i>
        全量收益统计
      </el-button>
      <el-button type="danger" plain @click="showProfitStatisticsDialog" class="function-btn">
        <i class="el-icon-trend-charts"></i>
        收益统计
      </el-button>
      <el-button type="warning" plain @click="showTProfitChartDialog(true)" class="function-btn">
        <i class="el-icon-pie-chart"></i>
        全量统计
      </el-button>
      <el-button type="info" plain @click="goToStockStatistics" class="function-btn">
        <i class="el-icon-view"></i>
        查看统计
      </el-button>
      <el-button type="primary" plain @click="goToStockPriceChart" class="function-btn">
        <i class="el-icon-data-line"></i>
        股价曲线
      </el-button>
      <el-button type="success" plain @click="showBreakEvenCalculator" class="function-btn">
        <i class="el-icon-coin"></i>
        计算保本价格
      </el-button>

    </div>
    <!-- 修改后的网格区块 -->
    <div class="grid-section">
      <!-- 上面一个区块 -->
      <div class="grid-item top-item">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>股票持仓</span>
              <el-button style="float: right; padding: 3px 0" type="text" @click="goToStockTradingDetail">查看详情</el-button>
            </div>
          </template>
          <div class="content">
            <!-- 上半部分是很多按钮,每个按钮显示一个股票名称 -->
            <div class="stock-buttons-container">
              <button class="scroll-arrow left-arrow" @click="scrollLeft">‹</button>
              <div class="stock-buttons" ref="stockButtons">
                <el-button
                    v-for="(stock, index) in stockList"
                    :key="index"
                    @click="selectStock(index)"
                    class="stock-button"
                    :class="{ 'selected-stock': selectedStockIndex === index }"
                >
                  {{ stock.stockName }}
                  <span v-if="selectedStockIndex === index" class="selected-indicator">★</span>
                </el-button>
              </div>
              <button class="scroll-arrow right-arrow" @click="scrollRight">›</button>
            </div>

            <!-- 下半部分是这个股票统计的数据-->
            <div class="stock-statistics " v-if="selectedStockIndex >= 0 && selectedStockIndex < stockList.length && this.latestStockData">
              <el-row type="flex" :gutter="10" style="flex-wrap: wrap;">
                <div
                    v-for="item in latestDataItems"
                    :key="item.key"
                    style="width: 185px; margin: 0 10px 10px 0;"
                >
                  <div 
                    class="stat-card" 
                    :class="{ 'clickable': item.title === '做T收益' }"
                    :style="{ cursor: item.title === '做T收益' ? 'pointer' : 'default' }"
                    @click="item.title === '做T收益' && showTProfitChartDialog(false)"
                  >
                    <div class="stat-title">{{ item.title }}</div>
                    <div class="stat-value">{{ item.value }} <span class="stat-unit" v-if="item.unit">{{ item.unit }}</span></div>
                  </div>
                </div>
              </el-row>
            </div>

            <!-- 默认提示 -->
            <div class="no-selection" v-else>
              <p>请选择一个股票查看详细信息</p>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 下面三个区块 -->
      <div class="grid-item bottom-item">
        <div class="bottom-grid">
          <!-- 当前股票池 -->
          <div class="grid-item">
            <el-card class="box-card">
              <template #header>
                <div class="card-header">
                  <span>当前股票池</span>
                  <el-button 
                    type="text" 
                    @click="showHistoricalPosition" 
                    style="margin-left: auto; color: #409eff; font-size: 14px; padding: 6px 12px; border-radius: 6px; transition: all 0.3s ease;"
                    onmouseover="this.style.backgroundColor='#f0f7ff'; this.style.color='#66b1ff'; this.style.transform='translateY(-1px)';"
                    onmouseout="this.style.backgroundColor='transparent'; this.style.color='#409eff'; this.style.transform='translateY(0)';"
                    onmousedown="this.style.transform='scale(0.95) translateY(-1px)';"
                    onmouseup="this.style.transform='scale(1) translateY(-1px)';"
                  >
                    <i class="el-icon-time" style="margin-right: 4px; font-size: 13px;"></i>
                    历史持仓
                  </el-button>
                </div>
              </template>
              <div class="content">
                <div v-if="stockPoolList.length > 0" class="stock-pool-grid">
                  <div v-for="item in stockPoolList" :key="item.id" class="stock-pool-box"  @click="fillBuyFormFromPool(item)" style="cursor: pointer;touch-action: manipulation;">
                    <div class="stock-box-content">
                      <div class="stock-shares">{{ item.buyShares }}股</div>
                      <div class="stock-price">¥{{ item.buyPrice }}</div>
                    </div>
                  </div>
                </div>
                <div v-else class="empty-pool">
                  <p>暂无股票池数据</p>
                </div>
              </div>
            </el-card>
          </div>

          <div class="grid-item">
            <el-card class="box-card">
              <template #header>
                <div class="card-header">
                  <span>股票待买入池</span>
                </div>
              </template>
              <div class="content">
                <div v-if="stockPendingBuyPoolList.length > 0" class="stock-pool-grid">
                  <div v-for="item in stockPendingBuyPoolList" :key="item.id" class="stock-pool-box" @click="fillSellFormFromPool(item)" style="cursor: pointer;touch-action: manipulation;">
                    <div class="stock-box-content">
                      <div class="stock-shares">{{ item.buyShares }}股</div>
                      <div class="stock-price">¥{{ item.buyPrice }}</div>
                    </div>
                  </div>
                </div>
                <div v-else class="empty-pool">
                  <p>暂无待买入股票数据</p>
                </div>
              </div>
            </el-card>
          </div>

          <div class="grid-item" ref="tTradeSection">
            <el-card class="box-card">
              <template #header>
                <div class="card-header">
                  <span>做T操作</span>
                </div>
              </template>
              <div class="content">
                <div class="t-trade-form">
                  <div class="form-row">
                    <div class="form-group">
                      <label>买入股票数</label>
                      <el-input
                          v-model="tTradeForm.buyQuantity"
                          placeholder="请输入买入数量"
                          type="number"
                          min="0"
                          ref="buyQuantity"
                      />
                    </div>

                    <div class="form-group">
                      <label>买入股价</label>
                      <el-input
                          v-model="tTradeForm.buyPrice"
                          placeholder="请输入买入价格"
                          type="number"
                          min="0"
                          step="0.01"
                      />
                    </div>
                  </div>
                  <div class="form-row">
                    <div class="form-group">
                      <label>卖出股票数</label>
                      <el-input
                          v-model="tTradeForm.sellQuantity"
                          placeholder="请输入卖出数量"
                          type="number"
                          min="0"
                          ref="sellQuantity"
                      />
                    </div>

                    <div class="form-group">
                      <label>卖出股价</label>
                      <el-input
                          v-model="tTradeForm.sellPrice"
                          placeholder="请输入卖出价格"
                          type="number"
                          min="0"
                          step="0.01"
                      />
                    </div>
                  </div>
                  <div class="form-actions">
                    <el-button
                        type="warning"
                        @click="clearPoolState"
                        :disabled="!poolType"
                        :title="poolType ? '清除相关状态' : '当前无需清除'"
                        style="width: 48%;"
                    >
                      清除
                    </el-button>
                    <el-button
                        type="primary"
                        @click="handleTTradeSubmit"
                        style="width: 48%;"
                    >
                      提交做T操作
                    </el-button>
                  </div>
                </div>
              </div>
            </el-card>
          </div>
        </div>
      </div>
    </div>

    <!-- 做T收益曲线弹窗 -->
    <el-dialog
      v-model="showTProfitChart"
      :title="`${selectedStock.stockName} 做T收益曲线`"
      width="80%"
      :before-close="handleCloseChart"
      :align-center="true"
    >
      <TProfitChart 
        :title="`${selectedStock.stockName} 做T收益曲线`"
        :stockName="selectedStock.stockName"
        :stockCode="selectedStock.stockCode"
        :type="year"
      />
    </el-dialog>

    <!-- 待买入池监控弹窗 -->
    <el-dialog
      v-model="pendingBuyDialogVisible"
      title="待买入池股价监控"
      width="90%"
      :before-close="handlePendingBuyClose"
      :align-center="true"
    >
      <StockPendingBuyMonitor />
    </el-dialog>

    <!-- 收益统计弹窗 -->
    <el-dialog
      title="收益统计"
       v-model="profitStatisticsDialogVisible"
      width="40%"
      :before-close="handleProfitStatisticsClose"
      :align-center="true"
    >
      <ProfitStatistics 
        :stockCode="selectedStock.stockCode"
        :stockName="selectedStock.stockName"/>
    </el-dialog>

    <el-dialog
      title="全量收益统计"
      v-model="allProfitDialogVisible"
      width="85%"
      :before-close="handleAllProfitClose"
      :align-center="true"
    >
      <AllProfitStatistics />
    </el-dialog>

    <!-- 历史持仓弹窗 -->
    <el-dialog
      v-model="showHistoricalPositionDialog"
      :title="`${selectedStock.stockName} 历史持仓`"
      width="80%"
      :before-close="handleHistoricalPositionClose"
      :align-center="true"
    >
      <HistoricalPosition 
        v-show="showHistoricalPositionDialog"
        :stock-code="selectedStock.stockCode"
        :stock-name="selectedStock.stockName"
      />
    </el-dialog>

    <!-- 保本价格计算器组件 -->
    <BreakEvenCalculator
      v-if="breakEvenCalculatorVisible"
      :visible="breakEvenCalculatorVisible"
      @update:visible="breakEvenCalculatorVisible = $event"
      :current-stock-data="currentStockDataForBreakEven"
    />

  </div>

</template>

<script>
import { useRouter } from 'vue-router'
import { listAllAccountSummary } from '@/api/account'
import { getStockList } from '@/api/stockTrading'
import { listStockPool, delStockPool, addStockPool } from '@/api/stockPool' // 添加这行导入
import { saveStockTTransaction } from '@/api/stockTTransaction'
import { listStockPendingBuyPool, addStockPendingBuyPool,delStockPendingBuyPool } from '@/api/stockPendingBuyPool'
import { getStockLatestData  } from '@/api/stockStatistics'
import TProfitChart from '@/components/TProfitChart.vue'
import StockPendingBuyMonitor from '@/components/StockPendingBuyMonitor.vue'
import ProfitStatistics from '@/components/ProfitStatistics.vue'
import AllProfitStatistics from '@/components/AllProfitStatistics.vue'
import HistoricalPosition from '@/components/HistoricalPosition.vue'
import BreakEvenCalculator from '@/components/BreakEvenCalculator.vue'

export default {
  name: 'Dashboard',
  components: {
    TProfitChart,
    StockPendingBuyMonitor,
    ProfitStatistics,
    AllProfitStatistics,
    HistoricalPosition,
    BreakEvenCalculator
  },
  data() {
    return {
      allProfitDialogVisible: false,
      showTProfitChart: false,
      isAllTProfitChart: false,
      profitStatisticsDialogVisible: false,
      pendingBuyDialogVisible: false,
      accountSummaryList: [],
      totalInvestment: 0,
      stockTradingList: [],
      stockList: [],
      selectedStockIndex: 0,
      stockPoolList: [], // 添加股票池数据
      stockPendingBuyPoolList: [], // 待买入池数据
      latestStockData: null, // 新增：存储选中股票的最新统计数据
      // 添加做T操作表单数据
      tTradeForm: {
        sellQuantity: '',
        sellPrice: '',
        buyQuantity: '',
        buyPrice: ''
      },
      // 做T时需要删除的股票池
      poolType:'',
      deleteStockPoolId:'',
      // 历史持仓相关
      showHistoricalPositionDialog: false,
      // 保本价格计算器相关
      breakEvenCalculatorVisible: false
    }
  },
  computed: {
    selectedStock() {
      if (this.selectedStockIndex >= 0 && this.selectedStockIndex < this.stockList.length) {
        return this.stockList[this.selectedStockIndex];
      }
      return {};
    },
    // 新增：计算属性，用于保本价格计算器的数据
    currentStockDataForBreakEven() {
      if (!this.latestStockData) return {}
      return {
        currentPrice: this.latestStockData.currentPrice || 0,
        totalShares: this.latestStockData.totalShares || 0,
        profitLoss: this.latestStockData.profitLoss || 0,
        stockName: this.selectedStock.stockName || '',
        stockCode: this.selectedStock.stockCode || ''
      }
    },
    // 新增：计算属性，用于生成卡片数据
    latestDataItems() {
      if (!this.latestStockData) return [];
      return [
        {
          key: 'totalShares',
          title: '总股数',
          value: this.latestStockData.totalShares || 0,
          unit: '股'
        },
        {
          key: 'profitLoss',
          title: '盈亏',
          value: this.latestStockData.profitLoss || 0,
          unit: '元'
        },
        {
          key: 'currentPrice',
          title: '当日价格',
          value: this.latestStockData.currentPrice || 0,
          unit: '元'
        },
       {
          key: 'breakEvenPrice',
          title: '保本价',
          value: this.latestStockData.breakEvenPrice || '0.00',
          unit: '元'
        },
        {
          key: 'marketValue',
          title: '总市值',
          value: this.latestStockData.marketValue || '0.00',
          unit: '元'
        },
        {
          key: 'tProfit',
          title: '做T收益',
          value: this.latestStockData.tProfit || '0.00',
          unit: '元'
        },
        {
          key: 'numberTrades',
          title: '做T次数',
          value: this.latestStockData.numberTrades || 0,
          unit: '次'
        },
        {
          key: 'successRate',
          title: '成功率',
          value: this.latestStockData.successRate || '0.00%',
          unit: '%'
        },
        {
          key: 'date',
          title: '更新日期',
          value: this.latestStockData.date || '-',
          unit: ''
        }
      ];
    }
  },
  created() {
    this.loadAccountSummaryData();
    this.loadStockList().then(() => {
      // 等待股票列表加载完成后再加载股票池和待买入池数据
      if (this.stockList.length > 0) {
        this.selectedStockIndex = 0; // 默认选中第一个股票
        this.loadStockPool();
        this.loadStockPendingBuyPool();
        this.loadLatestStockData(); // 加载第一个股票的最新数据
      }
    });
  },
  methods: {
    showAllProfitStatistics() {
      this.allProfitDialogVisible = true
    },
    handleAllProfitClose() {
      this.allProfitDialogVisible = false
    },
    showProfitStatisticsDialog() {
      this.isAllTProfitChart = false;
      this.profitStatisticsDialogVisible = true
    },
    handleProfitStatisticsClose() {
      this.profitStatisticsDialogVisible = false
    },
    showPendingBuyMonitor() {
      this.pendingBuyDialogVisible = true
    },
    handlePendingBuyClose() {
      this.pendingBuyDialogVisible = false
    },
    showTProfitChartDialog(status) {
      this.isAllTProfitChart = Boolean(status);
      this.showTProfitChart = true;
    },
    handleCloseChart() {
      this.showTProfitChart = false;
    },
    showHistoricalPosition() {
      // 检查是否选择了股票
      if (this.selectedStockIndex < 0 || this.selectedStockIndex >= this.stockList.length) {
        this.$message.warning('请先选择一个股票')
        return
      }
      
      // 获取选中的股票
      const selectedStock = this.stockList[this.selectedStockIndex]
      if (!selectedStock || !selectedStock.stockCode) {
        this.$message.warning('无效的股票信息')
        return
      }
      
      this.showHistoricalPositionDialog = true;
    },
    handleHistoricalPositionClose() {
      this.showHistoricalPositionDialog = false;
    },

    // 修改清除状态的方法
    clearPoolState() {
      if (!this.poolType) {
        this.$message.info('当前无需清除')
        return
      }

      this.poolType = ''
      this.deleteStockPoolId = ''
      this.tTradeForm = {
        sellQuantity: '',
        sellPrice: '',
        buyQuantity: '',
        buyPrice: ''
      }
      this.$message.success('已清除相关状态')
    },
    goToAccountSummary() {
      this.$router.push('/account-summary')
    },

    loadAccountSummaryData() {
      listAllAccountSummary().then(response => {
        if (response.code === 200) {
          this.accountSummaryList = response.data
          this.totalInvestment = response.data.reduce((sum, item) => {
            return sum + (parseFloat(item.totalInvestment) || 0)
          }, 0)
        } else {
          console.error('获取账户汇总数据失败:', response.msg)
          this.$message.error('获取账户汇总数据失败: ' + response.msg)
        }
      }).catch(error => {
        console.error('获取账户汇总数据时发生错误:', error)
        this.$message.error('获取账户汇总数据时发生错误')
      })
    },

    formatCurrency(value) {
      if (!value) return '0.00'
      return parseFloat(value).toLocaleString('zh-CN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
      })
    },

    goToStockTradingDetail() {
      // 检查是否选择了股票
      if (this.selectedStockIndex < 0 || this.selectedStockIndex >= this.stockList.length) {
        this.$message.warning('请先选择一个股票')
        return
      }

      // 获取选中的股票
      const selectedStock = this.stockList[this.selectedStockIndex]

      // 使用query参数传递股票编码和名称
      this.$router.push({
        path: '/stock-trading-list',
        query: {
          stockCode: selectedStock.stockCode,
          stockName: selectedStock.stockName,
          from: 'home'
        }
      })
    },

    selectStock(index) {
      this.selectedStockIndex = index;
      this.loadStockPool();
      this.loadStockPendingBuyPool();
      this.loadLatestStockData(); // 新增：加载最新统计数据
    },
    // 新增：加载选中股票的最新统计数据
    loadLatestStockData() {
      return new Promise((resolve, reject) => {
        if (this.selectedStockIndex < 0 || this.selectedStockIndex >= this.stockList.length) {
          resolve();
          return;
        }

        const selectedStock = this.stockList[this.selectedStockIndex];
        if (!selectedStock || !selectedStock.stockCode) {
          resolve();
          return;
        }

        // 导入stockStatistics API
        getStockLatestData(selectedStock.stockCode).then(response => {
          if (response.code === 200 && response.data) {
            // 根据新的接口重新实现一下这里的方法体
            const data = response.data;
            this.latestStockData = {
              totalShares: data.totalShares || 0,
              profitLoss: data.profitLoss || 0,
              currentPrice: data.currentPrice || 0,
              numberTrades: data.numberTrades || 0,
              successRate: data.successRate || '0.00%',
              tProfit: data.tprofit || '0.00',
              breakEvenPrice: data.breakEvenPrice || '0.00',
              marketValue: data.marketValue || '0.00',
              date: data.date || '-'
            };
            resolve();
          } else {
            console.error('获取股票统计数据失败:', response.message);
            this.latestStockData = null;
            reject(new Error(response.message || '获取股票统计数据失败'));
          }
        }).catch(error => {
            console.error('获取股票统计数据时发生错误:', error);
            this.latestStockData = null;
            reject(error);
        });
      });
    },
    scrollLeft() {
      const container = this.$refs.stockButtons;
      if (container) {
        container.scrollBy({
          left: -200,
          behavior: 'smooth'
        });
      }
    },

    scrollRight() {
      const container = this.$refs.stockButtons;
      if (container) {
        container.scrollBy({
          left: 200,
          behavior: 'smooth'
        });
      }
    },

    goToStockStatistics() {
      // 检查是否选择了股票
      if (this.selectedStockIndex < 0 || this.selectedStockIndex >= this.stockList.length) {
        this.$message.warning('请先选择一个股票')
        return
      }

      // 获取选中的股票
      const selectedStock = this.stockList[this.selectedStockIndex]

      // 使用query参数传递股票编码
      this.$router.push({
        path: '/stock-statistics',
        query: {
          stockCode: selectedStock.stockCode,
          stockName: selectedStock.stockName
        }
      })
    },

    goToStockPriceChart() {
      // 检查是否选择了股票
      if (this.selectedStockIndex < 0 || this.selectedStockIndex >= this.stockList.length) {
        this.$message.warning('请先选择一个股票')
        return
      }

      // 获取选中的股票
      const selectedStock = this.stockList[this.selectedStockIndex]

      // 跳转到股价图表页面，并传递股票信息
      this.$router.push({
        path: '/stock-price-chart',
        query: {
          stockCode: selectedStock.stockCode,
          stockName: selectedStock.stockName,
          from: 'home'
        }
      })
    },

    loadStockList() {
      return getStockList().then(response => {
        if (response.code === 200) {
          this.stockList = response.data
        } else {
          console.error('获取股票列表数据失败:', response.msg)
          this.$message.error('获取股票列表数据失败: ' + response.msg)
        }
      }).catch(error => {
        console.error('获取股票列表数据时发生错误:', error)
        this.$message.error('获取股票列表数据时发生错误')
      })
    },

    loadStockPool() {
      listStockPool({"stockCode":this.stockList[this.selectedStockIndex].stockCode}).then(response => {
        if (response.code === 200) {
          this.stockPoolList = response.data
        } else {
          console.error('获取股票池数据失败:', response.msg)
          this.$message.error('获取股票池数据失败: ' + response.msg)
        }
      }).catch(error => {
        console.error('获取股票池数据时发生错误:', error)
        this.$message.error('获取股票池数据时发生错误')
      })
    },
    loadStockPendingBuyPool() {
      listStockPendingBuyPool({"stockCode":this.stockList[this.selectedStockIndex].stockCode}).then(response => {
        if (response.code === 200) {
          this.stockPendingBuyPoolList = response.data
        } else {
          console.error('获取待买入池数据失败:', response.msg)
          this.$message.error('获取待买入池数据失败: ' + response.msg)
        }
      }).catch(error => {
        console.error('获取待买入池数据时发生错误:', error)
        this.$message.error('获取待买入池数据时发生错误')
      })
    },
    // 添加做T操作提交方法
    handleTTradeSubmit() {
      // 获取表单数据
      const sellQuantity = this.tTradeForm.sellQuantity?.trim()
      const sellPrice = this.tTradeForm.sellPrice?.trim()
      const buyQuantity = this.tTradeForm.buyQuantity?.trim()
      const buyPrice = this.tTradeForm.buyPrice?.trim()

      // 检查是否有卖出操作
      const hasSell = sellQuantity || sellPrice
      // 检查是否有买入操作
      const hasBuy = buyQuantity || buyPrice

      // 如果没有输入任何数据
      if (!hasSell && !hasBuy) {
        this.$message.warning('请至少填写卖出或买入操作信息')
        return
      }

      // 验证卖出操作的完整性
      if (hasSell) {
        if (!sellQuantity || !sellPrice) {
          this.$message.warning('卖出操作需要同时填写卖出股票数和卖出股价')
          return
        }
        const sellQty = parseInt(sellQuantity)
        const sellPrc = parseFloat(sellPrice)

        if (isNaN(sellQty) || sellQty <= 0 || isNaN(sellPrc) || sellPrc <= 0) {
          this.$message.warning('卖出股票数和卖出股价必须是大于0的数值')
          return
        }
      }

      // 验证买入操作的完整性
      if (hasBuy) {
        if (!buyQuantity || !buyPrice) {
          this.$message.warning('买入操作需要同时填写买入股票数和买入股价')
          return
        }
        const buyQty = parseInt(buyQuantity)
        const buyPrc = parseFloat(buyPrice)

        if (isNaN(buyQty) || buyQty <= 0 || isNaN(buyPrc) || buyPrc <= 0) {
          this.$message.warning('买入股票数和买入股价必须是大于0的数值')
          return
        }
      }

      // 检查是否选择了股票
      if (this.selectedStockIndex < 0 || this.selectedStockIndex >= this.stockList.length) {
        this.$message.warning('请先选择要操作的股票')
        return
      }

      // 获取选中的股票信息
      const selectedStock = this.stockList[this.selectedStockIndex]

      // 转换为数字类型
      const sellQty = hasSell ? parseInt(sellQuantity) : 0
      const sellPrc = hasSell ? parseFloat(sellPrice) : 0
      const buyQty = hasBuy ? parseInt(buyQuantity) : 0
      const buyPrc = hasBuy ? parseFloat(buyPrice) : 0

      // 前端计算收益
      let tprofit = 0
      let operationDesc = ''

      if (hasSell && hasBuy) {
        // 完整做T操作：卖出收益 - 买入成本
        tprofit = (sellQty * sellPrc) - (buyQty * buyPrc) - 2
        operationDesc = `做T操作：卖出${sellQty}股 @ ¥${sellPrc}，买入${buyQty}股 @ ¥${buyPrc}`
      } else if (hasSell) {
        // 仅卖出：卖出收益
        tprofit = 0
        // 调用新方法：将卖出的股票加入待买入池
        this.addToPendingBuyPool(selectedStock, sellPrc, sellQty);
        // 如果只有卖出操作,就不是做T操作,将卖出的股票加入股票待买入池
        return;
      } else {
        // 仅买入：买入成本（负值）
        tprofit = 0
        operationDesc = `买入操作：买入${buyQty}股 @ ¥${buyPrc}`
        // 如果只有买入操作,就不是做T操作,将买入的股票加入当前股票池
        this.addToCurrentPool(selectedStock, buyPrc, buyQty);
        return;
      }

      // 准备API请求数据
      const transactionData = {
        stockCode: selectedStock.stockCode,
        stockName: selectedStock.stockName,
        transactionDate: new Date().toISOString().split('T')[0], // 当前日期
        buyPrice: hasBuy ? buyPrc : null,
        buyQuantity: hasBuy ? buyQty : null,
        sellPrice: hasSell ? sellPrc : null,
        sellQuantity: hasSell ? sellQty : null,
        tprofit: tprofit.toFixed(2) // 前端计算的收益，保留2位小数
      }

      // 显示确认信息
      const confirmMessage = `确认对 ${selectedStock.stockName}(${selectedStock.stockCode}) 进行${operationDesc}，预计收益：¥${tprofit.toFixed(2)}`

      this.$confirm(confirmMessage, '确认操作', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        // 调用API保存交易记录
        return saveStockTTransaction(transactionData)
      }).then(response => {
        if (response.code === 200) {
          this.$message.success('交易记录保存成功')
          // 清空表单
          this.tTradeForm = {
            sellQuantity: '',
            sellPrice: '',
            buyQuantity: '',
            buyPrice: ''
          }
        } else {
          this.$message.error('保存失败：' + response.msg)
        }
      }).then(()=>{
        return this.deleteStockPoolById();
      }).then(response => {
        if(response != null && response.code === 200) {
          // 刷新数据
          this.loadStockPendingBuyPool();
          this.loadStockPool();
          this.poolType = null;
          this.deleteStockPoolId = null;
        }
      }).catch(error => {
        if (error !== 'cancel') {
          console.error('保存交易记录时发生错误:', error)
          this.$message.error('保存交易记录时发生错误')
        }
      })
    },
    // 添加新方法：仅卖出操作时将股票加入待买入池
    addToPendingBuyPool(stock, sellPrice, sellQuantity) {
      const pendingBuyData = {
        stockCode: stock.stockCode,
        stockName: stock.stockName,
        sellDate: new Date().toISOString().split('T')[0], // 当前日期
        buyPrice: sellPrice, // 使用卖出价格作为买入参考价
        buyShares: sellQuantity // 卖出数量作为待买入数量
      }

      // 调用API添加待买入池
      this.$confirm(`确认将 ${stock.stockName}(${stock.stockCode}) 加入待买入池？\n卖出价：¥${sellPrice}，数量：${sellQuantity}股`, '确认操作', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        return addStockPendingBuyPool(pendingBuyData)
      }).then(response => {
        if (response.code === 200) {
          this.$message.success('已加入待买入池')
          this.tTradeForm = {
            sellQuantity: '',
            sellPrice: '',
            buyQuantity: '',
            buyPrice: ''
          }
          this.loadStockPendingBuyPool() // 刷新待买入池数据
        } else {
          this.$message.error('添加失败：' + response.msg)
        }
      }).catch(error => {
        if (error !== 'cancel') {
          console.error('添加到待买入池时发生错误:', error)
          this.$message.error('添加到待买入池时发生错误')
        }
      })
    },
    // 添加新方法：仅买入操作时将股票加入当前股票池
    addToCurrentPool(stock, buyPrice, buyQuantity) {
      const poolData = {
        stockCode: stock.stockCode,
        stockName: stock.stockName,
        buyDate: new Date().toISOString().split('T')[0], // 当前日期
        buyPrice: buyPrice,
        buyShares: buyQuantity
      }

      // 调用API添加股票池
      this.$confirm(`确认将 ${stock.stockName}(${stock.stockCode}) 加入当前股票池？\n买入价：¥${buyPrice}，数量：${buyQuantity}股`, '确认操作', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        return addStockPool(poolData)
      }).then(response => {
        if (response.code === 200) {
          this.$message.success('已加入股票池')
          this.tTradeForm = {
            sellQuantity: '',
            sellPrice: '',
            buyQuantity: '',
            buyPrice: ''
          }
          this.loadStockPool() // 刷新股票池数据
        } else {
          this.$message.error('添加失败：' + response.msg)
        }
      }).catch(error => {
        if (error !== 'cancel') {
          console.error('添加到股票池时发生错误:', error)
          this.$message.error('添加到股票池时发生错误')
        }
      })
    },
    // 添加方法：从股票池或待买入池填充卖出表单
    fillSellFormFromPool(item) {
      this.poolType = 'sell';
      this.deleteStockPoolId = item.id;
      // 将股票池中的数据填入做T操作的卖出表单
      this.tTradeForm.sellQuantity = item.buyShares.toString()
      this.tTradeForm.sellPrice = item.buyPrice.toString()
      this.tTradeForm.buyQuantity = null
      this.tTradeForm.buyPrice = null
      // 提供用户反馈
      this.$message.success(`已将 ${item.stockName} 的数据填入卖出表单`)
      // 聚焦到买入数量输入框
      this.$nextTick(() => {
        if (this.$refs.buyQuantity) {
          this.$refs.buyQuantity.focus()
          console.log('已聚焦到买入数量输入框')
        }
      })
    },
    fillBuyFormFromPool(item) {
      this.poolType = 'buy';
      this.deleteStockPoolId = item.id;
      // 将股票池中的数据填入做T操作的卖出表单
      this.tTradeForm.buyQuantity = item.buyShares.toString()
      this.tTradeForm.buyPrice = item.buyPrice.toString()
      this.tTradeForm.sellQuantity = null
      this.tTradeForm.sellPrice = null
      // 提供用户反馈
      this.$message.success(`已将 ${item.stockName} 的数据填入买入表单`)
      // 聚焦到卖出数量输入框
      this.$nextTick(() => {
        if (this.$refs.sellQuantity) {
          this.$refs.sellQuantity.focus()
          console.log('已聚焦到卖出数量输入框')
        }
      })
    },
    deleteStockPoolById(){
      if(this.poolType == 'buy'){
        return delStockPool(this.deleteStockPoolId)
      }else if(this.poolType == 'sell'){
        return delStockPendingBuyPool(this.deleteStockPoolId)
      }
      return null;
    },
    // 保本价格计算器相关方法
    showBreakEvenCalculator() {
      console.log('点击了计算保本价格按钮')
      // 先尝试加载最新数据，确保股票名称能够正确显示
      this.loadLatestStockData().then(() => {
        console.log('最新数据加载完成，显示保本价格计算器')
        this.breakEvenCalculatorVisible = true
        console.log('设置breakEvenCalculatorVisible为true:', this.breakEvenCalculatorVisible)
      }).catch(error => {
        console.error('加载最新数据失败:', error)
        // 即使加载失败，也显示对话框，但会显示警告信息
        this.breakEvenCalculatorVisible = true
      })
    }
  }
}
</script>

<style scoped>
.dashboard-container {
  width: 100%;
  height: 100vh;
  padding: 0;
  margin: 0;
  box-sizing: border-box;
  overflow: hidden;
}

.top-section {
  width: 100%;
  padding:  20px 20px 0px 20px;
  box-sizing: border-box;
  margin-top: -10px;
}

.account-summary-card {
  height: 100%;
}

/* 在现有的样式部分添加以下规则 */
.el-card__body {
  padding: 0;
}

.account-summary-content {
  margin: 0;
  padding: 0;
}

.account-summary-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 20px;
}

.summary-list {
  flex: 1;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  gap: 15px;
}

.summary-item {
  display: flex;
  gap: 15px; /* 减小间距 */
  padding: 10px; /* 减小内边距 */
  border: 1px solid #e1e1e1;
  border-radius: 6px; /* 稍微减小圆角 */
  width: calc(33.33% - 10px); /* 每行三个 */
  box-sizing: border-box;
  background-color: #fafafa;
  transition: all 0.3s ease;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.summary-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  border-color: #409eff;
}

/* 🌊 水池主题的股票池样式 */
.stock-pool-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(85px, 1fr));
  gap: 8px;
  padding: 15px;
  max-height: 320px;
  overflow-y: auto;
  background: linear-gradient(135deg, #f0f9ff 0%, #e6f7ff 100%);
  border-radius: 12px;
  border: 1px solid #b3d9ff;
  box-shadow: inset 0 2px 8px rgba(24, 144, 255, 0.1);
}

/* 水滴样式的股票卡片 */
.stock-pool-box {
  background: linear-gradient(145deg, #ffffff 0%, #f8fbff 100%);
  border: 1px solid #91d5ff;
  border-radius: 50% 50% 50% 50% / 60% 60% 40% 40%;
  padding: 12px 6px;
  text-align: center;
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
  cursor: pointer;
  min-height: 65px;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow:
      0 4px 12px rgba(24, 144, 255, 0.15),
      0 2px 4px rgba(0, 0, 0, 0.08);
  position: relative;
  overflow: hidden;
}

/* 水滴波纹效果 */
.stock-pool-box::before {
  content: '';
  position: absolute;
  top: -50%;
  left: -50%;
  width: 200%;
  height: 200%;
  background: radial-gradient(circle, rgba(24, 144, 255, 0.1) 0%, transparent 70%);
  transform: scale(0);
  transition: transform 0.6s ease;
}

.stock-pool-box:hover::before {
  transform: scale(1);
}

.stock-pool-box:hover {
  transform: translateY(-4px) scale(1.05);
  box-shadow:
      0 8px 24px rgba(24, 144, 255, 0.25),
      0 4px 8px rgba(0, 0, 0, 0.12);
  border-color: #1890ff;
  background: linear-gradient(145deg, #ffffff 0%, #e6f7ff 100%);
}

/* 水波纹动画 */
@keyframes ripple {
  0% {
    transform: scale(0);
    opacity: 1;
  }
  100% {
    transform: scale(1);
    opacity: 0;
  }
}

.stock-pool-box:active {
  animation: ripple 0.6s ease-out;
}

.stock-box-content {
  display: flex;
  flex-direction: column;
  gap: 3px;
  width: 100%;
  z-index: 1;
  position: relative;
}

/* 股票数量 - 水滴中的珍珠 */
.stock-shares {
  font-size: 13px;
  font-weight: 700;
  color: #1890ff;
  line-height: 1.2;
  text-shadow: 0 1px 2px rgba(24, 144, 255, 0.3);
}

/* 股票价格 - 水面反光 */
.stock-price {
  font-size: 11px;
  color: #52c41a;
  font-weight: 600;
  line-height: 1.2;
  text-shadow: 0 1px 1px rgba(82, 196, 26, 0.2);
}

/* 价格颜色区分 - 水面倒影效果 */
.stock-price.negative {
  color: #ff4d4f;
  text-shadow: 0 1px 1px rgba(255, 77, 79, 0.2);
}

/* 响应式优化 - 水池自适应 */
@media (max-width: 1200px) {
  .stock-pool-grid {
    grid-template-columns: repeat(auto-fill, minmax(80px, 1fr));
    gap: 6px;
    padding: 12px;
  }

  .stock-pool-box {
    min-height: 60px;
    padding: 10px 5px;
  }
}

@media (max-width: 768px) {
  .stock-pool-grid {
    grid-template-columns: repeat(auto-fill, minmax(75px, 1fr));
    gap: 5px;
    padding: 10px;
  }

  .stock-pool-box {
    min-height: 55px;
    padding: 8px 4px;
  }

  .stock-shares {
    font-size: 12px;
  }

  .stock-price {
    font-size: 10px;
  }
}

/* 水池滚动条 - 水波纹效果 */
.stock-pool-grid::-webkit-scrollbar {
  width: 6px;
}

.stock-pool-grid::-webkit-scrollbar-track {
  background: linear-gradient(180deg, #f0f9ff 0%, #e6f7ff 100%);
  border-radius: 3px;
}

.stock-pool-grid::-webkit-scrollbar-thumb {
  background: linear-gradient(180deg, #91d5ff 0%, #1890ff 100%);
  border-radius: 3px;
  box-shadow: 0 0 4px rgba(24, 144, 255, 0.3);
}

.stock-pool-grid::-webkit-scrollbar-thumb:hover {
  background: linear-gradient(180deg, #69c0ff 0%, #40a9ff 100%);
}

/* 空状态 - 干涸的水池 */
.empty-pool {
  text-align: center;
  color: #096dd9;
  padding: 40px 0;
  font-size: 14px;
  background: linear-gradient(135deg, #f0f9ff 0%, #e6f7ff 100%);
  border-radius: 8px;
  border: 1px dashed #91d5ff;
}

.empty-pool p {
  margin: 0;
  opacity: 0.7;
}

.summary-total {
  min-width: 220px;
  padding: 20px;
  background: linear-gradient(135deg, #409eff, #66b1ff);
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  align-self: stretch;
  color: white;
  box-shadow: 0 4px 8px rgba(64, 158, 255, 0.3);
}

.info-item {
  display: flex;
  flex-direction: column;
  margin-bottom: 8px; /* 稍微减小间距 */
}

.info-item:last-child {
  margin-bottom: 0;
}

.info-item .label {
  font-size: 11px; /* 减小字体 */
  color: #666;
  margin-bottom: 3px; /* 减小间距 */
  font-weight: 500;
}

.info-item .value {
  font-size: 12px; /* 减小字体 */
  font-weight: 500;
}

.value-money {
  color: #67c23a;
  font-weight: 600;
}

.summary-total .value {
  font-size: 16px; /* 稍微减小字体 */
  font-weight: 600;
}

.value-total {
  font-size: 20px !important;
  color: white;
}

/* 修改网格布局样式 */
.grid-section {
  display: grid;
  grid-template-columns: 1fr;
  grid-template-rows: auto 1fr;
  grid-template-areas:
    "top"
    "bottom";
  gap: 20px;
  padding: 0 20px 20px 20px;
  box-sizing: border-box;
  height: calc(100vh - 200px);
}

.bottom-grid {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  gap: 20px;
  height: 100%;
}

.top-item {
  grid-area: top;
  margin-top: -30px; /* 将元素往上移动10px */
}

.bottom-item {
  grid-area: bottom;
  margin-top: -10px; /* 将元素往上移动10px */
}

/* 响应式设计 */
@media (max-width: 768px) {
  .bottom-grid {
    grid-template-columns: 1fr;
  }
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.content {
  padding: 10px 0;
  position: relative;
}

.stock-buttons-container {
  position: absolute;
  display: flex;
  align-items: center;
  justify-content: space-between; /* 使子元素在主轴上均匀分布 */
  height: 40px;
  padding: 0 5px;
  width: 100%; /* 确保容器占据全部宽度 */
}

/* 修改.stock-buttons样式 */
.stock-buttons {
  height: 40px;
  display: flex;
  flex-wrap: nowrap;
  overflow-x: auto;
  overflow-y: hidden;
  width: 90%;
  gap: 10px;
  padding: 5px 0px;
  border-bottom: 1px solid #ebeef5;
  /* 强制硬件加速以改善滚动性能 */
  -webkit-overflow-scrolling: touch;
  /* 添加滚动惯性 */
  scroll-behavior: smooth;
  z-index: 1;
}

/* 隐藏 WebKit 浏览器的滚动条 */
.stock-buttons::-webkit-scrollbar {
  display: none;
}

.stock-button {
  flex-shrink: 0; /* 防止按钮被压缩 */
  white-space: nowrap; /* 防止按钮内文字换行 */
  height: 32px;
  min-width: 100px; /* 增加最小宽度确保按钮足够宽 */
  /* 添加一些样式确保按钮正确显示 */
  padding: 0 15px; /* 增加内边距 */
  /* 添加鼠标样式 */
  cursor: grab;
}

/* 箭头按钮样式 */
.scroll-arrow {
  background: #f5f5f5;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  width: 24px;
  height: 24px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  font-weight: bold;
  color: #606266;
  transition: all 0.3s;
  z-index: 2;
  flex-shrink: 0;
}

.scroll-arrow:hover {
  background: #409eff;
  color: white;
  border-color: #409eff;
}

.scroll-arrow:active {
  transform: scale(0.92);
}

.left-arrow {
  margin-right: 5px;
}

.right-arrow {
  margin-left: 5px;
}

/* 添加按钮按下时的样式 */
.stock-button:active {
  cursor: grabbing;
}

/* 新增股票统计数据样式 */
.stock-statistics {
  padding: 20px 0;
  margin-top: 50px;
}

.stat-label {
  font-weight: 500;
  color: #606266;
}

.stat-value {
  font-weight: 600;
  color: #303133;
}

.stat-value.profit {
  color: #67c23a;
}

.stat-value.loss {
  color: #f56c6c;
}

.no-selection {
  text-align: center;
  padding: 40px 0;
  color: #909399;
}

/* 做T操作表单样式 */
.form-row {
  display: flex;
  gap: 15px;
  margin-bottom: 15px;
}

.form-group {
  flex: 1;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-size: 14px;
  color: #606266;
  font-weight: 500;
}

.form-actions {
  margin-top: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .form-row {
    flex-direction: column;
    gap: 10px;
  }
}

/* 添加悬停效果 */
.stock-pool-box {
  transition: all 0.3s ease;
}

.stock-pool-box:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

/* 添加点击时的视觉反馈 */
.stock-pool-box:active {
  transform: translateY(0);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 在现有样式末尾添加 */
.stock-pool-box {
  touch-action: manipulation; /* 关键：移除300ms延迟 */
  -webkit-tap-highlight-color: transparent;
}

/* 无动画的选中样式 - 直接替换现有样式 */
.stock-button.selected-stock {
  background-color: #409eff !important;
  color: white !important;
  border-color: #409eff !important;
  box-shadow: none !important;
  transform: none !important;
}

.stock-button.selected-stock .selected-indicator {
  color: white;
  font-weight: bold;
  margin-left: 5px;
}

/* 确保未选中状态样式清晰 */
.stock-button:not(.selected-stock) {
  background-color: #f5f5f5 !important;
  color: #606266 !important;
  border-color: #ebeef5 !important;
}

/* 移除所有过渡效果，确保立即切换 */
.stock-button {
  transition: none !important;
  animation: none !important;
}

/* 确保点击时立即生效 */
.stock-button:active {
  transform: none !important;
}

.stat-card {
  padding: 12px;
  background: linear-gradient(135deg, #ffffff 0%, #f5f7fa 100%);
  border-radius: 6px;
  text-align: center;
  border: 1px solid #e4e7ed;
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 3px 8px rgba(0, 0, 0, 0.12);
}

.stat-card.profit {
  background: linear-gradient(135deg, #f0f9ff 0%, #e6f7ff 100%);
  border-color: #91d5ff;
}

.stat-card.loss {
  background: linear-gradient(135deg, #fff2f0 0%, #fff1f0 100%);
  border-color: #ffccc7;
}

.stat-card.current {
  background: linear-gradient(135deg, #f6ffed 0%, #e6f7ff 100%);
  border-color: #b7eb8f;
}

.stat-title {
  font-size: 14px;
  opacity: 0.9;
  margin-bottom: 8px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
}

.stat-unit {
  font-size: 14px;
  opacity: 0.8;
  margin-left: 4px;
}

/* 添加可点击的统计卡片样式 */
.clickable {
  transform: translateY(-2px) scale(1.02);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
  border-color: #409eff;
}

/* 功能区域样式 */
.function-section {
width: 100%;
max-width: 1825px; 
margin: 10px auto 40px;  
padding: 20px;
box-sizing: border-box;
border-radius: 12px;
box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
display: flex;
gap: 12px;
justify-content: center;
align-items: center;
border: 1px solid #e9ecef;
}

.function-btn {
  padding: 12px 20px;
  font-size: 14px;
  font-weight: 500;
  border-radius: 8px;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 6px;
  min-width: 140px;
  justify-content: center;
}

.function-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.function-btn:active {
  transform: translateY(0);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.function-btn i {
  font-size: 16px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .function-section {
    padding: 15px;
    gap: 8px;
  }
  
  .function-btn {
    padding: 10px 16px;
    font-size: 13px;
    min-width: 120px;
  }
}

</style>